package com.twan.kotlinbase.util

import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.skydoves.powerspinner.OnSpinnerOutsideTouchListener
import com.skydoves.powerspinner.PowerSpinnerView
import com.twan.kotlinbase.R
import com.twan.kotlinbase.bean.Dict

object SpiUtils {

    // T 必须重写tostring, 其值为spi的值
    // initIndex 从0开始 ,表示要初始化的第几项数据,其中initIndex<datas.size
    fun <T> setSpi(spiView: PowerSpinnerView, datas: List<T>?,initIndex:Int=0, onselect: ((pos:Int, T)->Unit)?=null){
        if (datas.isNullOrEmpty()) return
        if (datas.size > 5) spiView.spinnerPopupHeight=500

        //初始化onselect,并默认选择第一个
        spiView.text = datas[initIndex].toString()
        onselect?.run {
            onselect(initIndex, datas[initIndex])
        }

        spiView.setOnTouchListener { _, _ ->
            spiView.getSpinnerRecyclerView().adapter?.notifyDataSetChanged()
            false
        }
        spiView.spinnerOutsideTouchListener = object : OnSpinnerOutsideTouchListener {
            override fun onSpinnerOutsideTouch(view: View, event: MotionEvent) {
                spiView.dismiss()
            }
        }
        spiView.getSpinnerRecyclerView().adapter= object : BaseQuickAdapter<T, BaseViewHolder>(R.layout.item_my_spi,datas.toMutableList()) {
            override fun convert(holder: BaseViewHolder, model: T) {
                var tv_desc=holder.getView<TextView>(R.id.tv_desc)
                var iv_check=holder.getView<ImageView>(R.id.iv_check)
                holder!!.setText(R.id.tv_desc, model.toString())
                if (spiView.tag !=null && (spiView.tag as T) == model){
                    iv_check.visibility=View.VISIBLE
                } else {
                    iv_check.visibility=View.GONE
                }
                tv_desc.setOnClickListener {
                    spiView.text = model.toString()
                    spiView.tag = model
                    onselect?.run {
                        onselect(holder.position,model!!)
                    }
                    spiView.dismiss()
                }
            }
        }.also {
            it.notifyDataSetChanged()
            it.setOnItemClickListener { adapter, view, position ->
                spiView.text = datas[position].toString()
                spiView.tag = datas[position]
                onselect?.run {
                    onselect(position,datas[position])
                }
                spiView.dismiss()
            }
        }
    }

}